import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:flutterdev/api/ApiService.dart';
import 'package:flutterdev/components/CustomWebView.dart';
import 'package:flutterdev/components/LoadingContainer.dart';
import 'package:flutterdev/constant/CommonConstant.dart';
import '../components/GridNav.dart';
import '../components/LocalNav.dart';
import '../components/SalesBox.dart';
import '../components/SearchBarWidget.dart';
import '../components/SubNav.dart';
import '../model/CommonModel.dart';
import '../model/ConfigModel.dart';
import '../model/GridNavModel.dart';
import '../model/SalesBoxModel.dart';
import '../utils/NavigatorUtil.dart';

/// 首页面
class HomePage extends StatefulWidget {
  static ConfigModel? configModel;

  const HomePage({super.key});

  @override
  HomePageState createState() => HomePageState();
}

final class HomePageState extends State<HomePage> {
  double appBarAlpha = 0;
  List<CommonModel> localNavList = [];
  List<CommonModel> bannerList = [];
  List<CommonModel> subNavList = [];
  GridNavModel? gridNavModel;
  SalesBoxModel? salesBoxModel;
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _onRefresh();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff5f5f5),
      body: LoadingContainer(
        isLoading: _loading,
        child: Stack(
          children: [
            MediaQuery.removePadding(
              removeTop: true,
              context: context,
              child: RefreshIndicator(
                onRefresh: _onRefresh,
                child: NotificationListener(
                  child: _homeList,
                  onNotification: (scrollNotification) {
                    if (scrollNotification is ScrollNotification &&
                        scrollNotification.depth == 0) {
                      _onScroll(scrollNotification.metrics.pixels);
                    }
                    return false;
                  },
                ),
              ),
            ),
            _appBar,
          ],
        ),
      ),
    );
  }

  /// 顶部标题栏
  Widget get _appBar {
    return Column(
      children: <Widget>[
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              //AppBar渐变遮罩背景
              colors: [Color(0x66000000), Colors.transparent],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
            height: 80.0,
            decoration: BoxDecoration(
              color: Color.fromARGB((appBarAlpha * 255).toInt(), 255, 255, 255),
            ),
            child: SearchBarWidget(
              searchBarType: appBarAlpha > 0.2
                  ? SearchBarType.homeLight
                  : SearchBarType.home,
              inputBoxClick: _jumpToSearch,
              speakClick: _jumpToSpeak,
              defaultText: CommonConstant.SEARCH_BAR_DEFAULT_TEXT,
              leftButtonClick: () {},
            ),
          ),
        ),
        Container(
          height: appBarAlpha > 0.2 ? 0.5 : 0,
          decoration: BoxDecoration(
            boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)],
          ),
        ),
      ],
    );
  }

  /// 拆分首页列表
  Widget get _homeList {
    return ListView(
      children: <Widget>[
        _bannerView,
        Padding(
          padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
          child: LocalNav(localNavList: localNavList),
        ),
        if (gridNavModel != null)
          Padding(
            padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
            child: GridNav(gridNavModel: gridNavModel!),
          ),
        Padding(
          padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: SubNav(subNavList: subNavList),
        ),
        if (salesBoxModel != null)
          Padding(
            padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
            child: SalesBox(salesBox: salesBoxModel!),
          ),
      ],
    );
  }

  Widget get _bannerView {
    return Container(
      height: 230,
      child: Swiper(
        itemCount: bannerList.length,
        autoplay: true,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: () {
              CommonModel model = bannerList[index];
              NavigatorUtil.push(
                context,
                CustomWebView(
                  url: model.url,
                  title: model.title,
                  hideAppBar: model.hideAppBar,
                ),
              );
            },
            child: Image.network(bannerList[index].icon!, fit: BoxFit.fill),
          );
        },
        pagination: SwiperPagination(),
      ),
    );
  }

  /// 获取首页数据
  Future<Null> _onRefresh() async {
    ApiService.requestHomeData()
        .then((result) {
          setState(() {
            HomePage.configModel = result.config;
            localNavList = result.localNavList;
            subNavList = result.subNavList;
            gridNavModel = result.gridNav;
            salesBoxModel = result.salesBox;
            bannerList = result.bannerList;
            _loading = false;
          });
        })
        .catchError((error) {
          setState(() {
            _loading = false;
          });
        });
  }

  /// 处理顶部标题栏滑动渐变效果
  _onScroll(offset) {
    double alpha = offset / CommonConstant.APPBAR_SCROLL_OFFSET;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      appBarAlpha = alpha;
    });
  }

  // 搜索
  _jumpToSearch() {}

  _jumpToSpeak() {}
}
